'use strict';
const db = uniCloud.database();
const roomsCollection = db.collection('rooms');
const floorsCollection = db.collection('floors');

exports.main = async (event, context) => {
	const { floor_id, room_number, price, room_type, images, furniture_list, introduction, token } = event;
	
	// 只检查token是否存在
	if (!token) {
		return {
			code: 401,
			message: '未登录'
		};
	}
	
	// 参数校验
	if (!floor_id) {
		return {
			code: 1,
			message: '缺少楼层ID参数'
		};
	}
	
	if (!room_number) {
		return {
			code: 2,
			message: '缺少房间号参数'
		};
	}
	
	if (!price || typeof price !== 'number' || price < 0) {
		return {
			code: 3,
			message: '价格参数无效，应为非负数'
		};
	}
	
	if (!room_type) {
		return {
			code: 4,
			message: '缺少户型参数'
		};
	}
	
	// 检查楼层是否存在
	const floorResult = await floorsCollection.doc(floor_id).get();
	if (!floorResult.data || floorResult.data.length === 0) {
		return {
			code: 5,
			message: '指定的楼层不存在'
		};
	}
	
	// 检查房间号是否已存在于该楼层
	const checkResult = await roomsCollection.where({
		floor_id: floor_id,
		room_number: room_number
	}).count();
	
	if (checkResult.total > 0) {
		return {
			code: 6,
			message: '该楼层下的房间号已存在'
		};
	}
	
	// 添加房间
	const addResult = await roomsCollection.add({
		floor_id: floor_id,
		room_number: room_number,
		price: price,
		room_type: room_type,
		status: 0, // 默认为空房
		images: images || [],
		furniture_list: furniture_list || [],
		introduction: introduction || '',
		create_time: new Date(),
		update_time: new Date()
	});
	
	return {
		code: 0,
		message: '房间添加成功',
		data: {
			id: addResult.id
		}
	};
}; 